```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>状态机设计模式：告别if-else地狱</title>
    <link href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <style>
        :root {
            --primary: #3b82f6;
            --primary-dark: #2563eb;
            --accent: #10b981;
            --text: #334155;
            --text-light: #64748b;
            --bg: #f8fafc;
        }
        
        body {
            font-family: 'Noto Sans SC', sans-serif;
            color: var(--text);
            background-color: var(--bg);
            line-height: 1.6;
        }
        
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Noto Serif SC', serif;
            font-weight: 600;
            color: #1e293b;
        }
        
        .drop-cap::first-letter {
            float: left;
            font-size: 4em;
            line-height: 0.8;
            margin-right: 0.1em;
            color: var(--primary);
            font-weight: bold;
        }
        
        .code-block {
            position: relative;
        }
        
        .code-block pre {
            border-radius: 0.5rem;
            background-color: #1e293b;
            padding: 1.5rem;
            overflow-x: auto;
        }
        
        .code-block .copy-btn {
            position: absolute;
            right: 0.5rem;
            top: 0.5rem;
            background-color: rgba(255,255,255,0.1);
            border: none;
            color: white;
            border-radius: 0.25rem;
            padding: 0.25rem 0.5rem;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .code-block:hover .copy-btn {
            opacity: 1;
        }
        
        .card {
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .mermaid {
            background-color: white;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
    </style>
</head>
<body class="antialiased">
    <!-- Hero Section -->
    <section class="relative py-20 bg-gradient-to-r from-blue-600 to-blue-400 text-white overflow-hidden">
        <div class="absolute inset-0 opacity-20" style="background-image: url('');"></div>
        <div class="container mx-auto px-6 relative z-10">
            <div class="max-w-3xl mx-auto text-center">
                <div class="inline-flex items-center px-4 py-2 bg-white bg-opacity-20 rounded-full mb-6">
                    <i class="fas fa-code text-lg mr-2"></i>
                    <span class="font-medium">设计模式</span>
                </div>
                <h1 class="text-4xl md:text-5xl font-bold mb-6 leading-tight">状态机设计模式</h1>
                <p class="text-xl md:text-2xl mb-8 leading-relaxed">告别if-else地狱，用优雅的状态转换实现复杂业务逻辑</p>
                <div class="flex justify-center space-x-4">
                    <a href="#concept" class="px-6 py-3 bg-white text-blue-600 font-medium rounded-lg hover:bg-opacity-90 transition-colors">
                        <i class="fas fa-book-open mr-2"></i>开始学习
                    </a>
                    <a href="#example" class="px-6 py-3 border-2 border-white text-white font-medium rounded-lg hover:bg-white hover:bg-opacity-10 transition-colors">
                        <i class="fas fa-code mr-2"></i>查看示例
                    </a>
                </div>
            </div>
        </div>
        <div class="absolute bottom-0 left-0 right-0 h-16 bg-white"></div>
    </section>

    <!-- Main Content -->
    <div class="container mx-auto px-6 py-12">
        <div class="max-w-4xl mx-auto">
            <!-- Intro Section -->
            <section class="mb-20">
                <div class="bg-white rounded-xl shadow-lg p-8">
                    <p class="text-xl text-gray-700 mb-6 drop-cap">还在为那些堆积如山的if-else语句头疼吗？每次需求变更，你是否都要在条件分支的迷宫中挣扎？我曾经维护过一个有着23层嵌套条件判断的"遗留代码"，那段经历让我发誓再也不写这样的代码。状态机设计模式不仅能让你的代码结构清晰，还能让复杂逻辑变得优雅简洁。</p>
                    <p class="text-xl text-gray-700 mb-6">当我第一次将一个1000行的条件判断重构为状态机后，不仅代码量减少了40%，bug也减少了80%！更重要的是，团队中的新成员只需一天就能理解整个流程，而不是之前需要的一周。</p>
                    <img src="https://cdn.nlark.com/yuque/0/2025/png/21449790/1749533452353-29449405-0606-428a-8b35-10ade749bc15.png" alt="状态机示例" class="w-full rounded-lg shadow-md mt-6">
                </div>
            </section>

            <!-- Concept Section -->
            <section id="concept" class="mb-20">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-blue-500 pl-4">一、状态机的基本概念</h2>
                
                <div class="space-y-12">
                    <!-- What is FSM -->
                    <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="p-8">
                            <h3 class="text-2xl font-bold mb-4 flex items-center">
                                <i class="fas fa-sitemap text-blue-500 mr-3"></i>
                                <span>1. 什么是有限状态机(FSM)</span>
                            </h3>
                            <p class="text-gray-700 mb-6">有限状态机（Finite State Machine，简称FSM）是一种数学模型，用于描述系统在不同状态之间的转换。它由三个基本元素组成：状态、事件和转换。简单来说，状态机就像一张地图，状态是地点，事件是路径，而转换则是从一个地点到另一个地点的旅程。</p>
                            
                            <div class="code-block mb-6">
                                <button class="copy-btn" onclick="copyCode(this)">
                                    <i class="fas fa-copy"></i>
                                </button>
                                <pre><code class="language-javascript">// 一个简单的状态机示例
const trafficLight = {
  state: 'red',
  transitions: {
    red: { change: 'green' },
    green: { change: 'yellow' },
    yellow: { change: 'red' }
  },
  dispatch(event) {
    this.state = this.transitions[this.state][event] || this.state;
    return this.state;
  }
};

console.log(trafficLight.state); // 'red'
trafficLight.dispatch('change');
console.log(trafficLight.state); // 'green'</code></pre>
                            </div>
                        </div>
                    </div>
                    
                    <!-- States, Events & Transitions -->
                    <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="p-8">
                            <h3 class="text-2xl font-bold mb-4 flex items-center">
                                <i class="fas fa-exchange-alt text-blue-500 mr-3"></i>
                                <span>2. 状态、事件与转换的关系</span>
                            </h3>
                            <p class="text-gray-700 mb-6">状态代表系统在特定时刻的情况；事件是触发状态变化的动作；转换则定义了在特定状态下，特定事件会导致系统进入哪个新状态。这三者构成了状态机的核心。</p>
                            <p class="text-gray-700 mb-6">想象一下咖啡机：它可以处于"待机"、"加热"、"制作咖啡"等状态。按下"开始"按钮这个事件会让它从"待机"转换到"加热"状态，而水温达到目标值这个事件则会让它从"加热"转换到"制作咖啡"状态。</p>
                            
                            <div class="mermaid mb-6">
                                stateDiagram-v2
                                    [*] --> 待机
                                    待机 --> 加热: 按下开始按钮
                                    加热 --> 制作咖啡: 水温达到目标
                                    制作咖啡 --> 待机: 完成制作
                            </div>
                        </div>
                    </div>
                    
                    <!-- Difference from if-else -->
                    <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="p-8">
                            <h3 class="text-2xl font-bold mb-4 flex items-center">
                                <i class="fas fa-code-branch text-blue-500 mr-3"></i>
                                <span>3. 状态机与传统if-else的本质区别</span>
                            </h3>
                            <p class="text-gray-700 mb-6">传统if-else是基于条件的编程，而状态机是基于状态的编程。这种思维方式的转变是本质区别。</p>
                            
                            <div class="grid md:grid-cols-2 gap-6">
                                <div>
                                    <h4 class="font-bold text-lg mb-2 text-red-600">if-else方式</h4>
                                    <div class="code-block">
                                        <button class="copy-btn" onclick="copyCode(this)">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                        <pre><code class="language-python"># 传统if-else方式
def process_order(order):
    if order.status == "new":
        if order.payment_verified:
            order.status = "paid"
            send_confirmation_email()
        else:
            verify_payment(order)
    elif order.status == "paid":
        if order.items_available:
            order.status = "shipping"
            prepare_shipment(order)
        else:
            order.status = "backorder"
            notify_backorder(order)
    # 更多嵌套条件...</code></pre>
                                    </div>
                                </div>
                                <div>
                                    <h4 class="font-bold text-lg mb-2 text-green-600">状态机方式</h4>
                                    <div class="code-block">
                                        <button class="copy-btn" onclick="copyCode(this)">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                        <pre><code class="language-python"># 状态机方式
class OrderStateMachine:
    def __init__(self):
        self.transitions = {
            "new": {"payment_verified": "paid", "payment_failed": "canceled"},
            "paid": {"items_available": "shipping", "items_unavailable": "backorder"},
            # 更多状态转换...
        }
        self.actions = {
            "new_to_paid": send_confirmation_email,
            "paid_to_shipping": prepare_shipment,
            # 更多动作...
        }
    
    def process_event(self, order, event):
        current_state = order.status
        next_state = self.transitions.get(current_state, {}).get(event)
        
        if next_state:
            action_key = f"{current_state}_to_{next_state}"
            if action_key in self.actions:
                self.actions[action_key](order)
            order.status = next_state</code></pre>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- If-else Hell Section -->
            <section class="mb-20">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-red-500 pl-4">二、if-else地狱的真实面目</h2>
                
                <div class="grid md:grid-cols-3 gap-6">
                    <!-- Maintenance Nightmare -->
                    <div class="card bg-white rounded-xl shadow-lg p-6">
                        <div class="text-red-500 text-3xl mb-4">
                            <i class="fas fa-bug"></i>
                        </div>
                        <h3 class="text-xl font-bold mb-3">1. 复杂条件分支的维护噩梦</h3>
                        <p class="text-gray-700">我曾经接手过一个在线商城的代码，其中订单处理逻辑有超过15个状态，每个状态下又有多种可能的操作。使用if-else实现的代码超过2000行，几乎没有人敢动它，因为没人能确定修改一处会不会影响其他地方。</p>
                    </div>
                    
                    <!-- Readability & Testability -->
                    <div class="card bg-white rounded-xl shadow-lg p-6">
                        <div class="text-red-500 text-3xl mb-4">
                            <i class="fas fa-eye-slash"></i>
                        </div>
                        <h3 class="text-xl font-bold mb-3">2. 代码可读性与可测试性的双重打击</h3>
                        <p class="text-gray-700">这种代码不仅难以阅读，也几乎不可能全面测试。测试覆盖所有条件组合需要编写数十甚至上百个测试用例，而且很难确保覆盖了所有边界情况。</p>
                    </div>
                    
                    <!-- Requirements Change -->
                    <div class="card bg-white rounded-xl shadow-lg p-6">
                        <div class="text-red-500 text-3xl mb-4">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <h3 class="text-xl font-bold mb-3">3. 需求变更时的连锁反应</h3>
                        <p class="text-gray-700">当产品经理说"我们需要在支付确认后增加一个欺诈检查步骤"时，你可能需要修改多处代码，而且很容易遗漏某些条件分支。这种连锁反应让简单的需求变更变成了高风险操作。</p>
                    </div>
                </div>
                
                <div class="mt-8 code-block">
                    <button class="copy-btn" onclick="copyCode(this)">
                        <i class="fas fa-copy"></i>
                    </button>
                    <pre><code class="language-java">// 噩梦般的if-else代码
public void processOrder(Order order) {
    if (order.getStatus().equals("NEW")) {
        if (order.getPaymentMethod().equals("CREDIT_CARD")) {
            if (validateCreditCard(order.getPaymentDetails())) {
                if (order.getAmount() > 1000) {
                    if (isWorkingHours()) {
                        requestManualReview(order);
                    } else {
                        scheduleReviewForNextDay(order);
                    }
                } else {
                    processPayment(order);
                    if (paymentSuccessful) {
                        order.setStatus("PAID");
                        // 更多嵌套...
                    }
                }
            }
        } else if (order.getPaymentMethod().equals("PAYPAL")) {
            // 另一堆嵌套条件...
        }
    } else if (order.getStatus().equals("PAID")) {
        // 更多嵌套条件...
    }
    // 还有数百行类似代码...
}</code></pre>
                </div>
            </section>

            <!-- Advantages Section -->
            <section class="mb-20">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-green-500 pl-4">三、状态机设计的核心优势</h2>
                
                <div class="grid md:grid-cols-3 gap-6">
                    <!-- Code Clarity -->
                    <div class="card bg-white rounded-xl shadow-lg p-6">
                        <div class="text-green-500 text-3xl mb-4">
                            <i class="fas fa-eye"></i>
                        </div>
                        <h3 class="text-xl font-bold mb-3">1. 代码结构的清晰度提升</h3>
                        <p class="text-gray-700">状态机将状态与行为明确分离，每个状态只关心自己能处理的事件，这使得代码结构清晰可见。</p>
                    </div>
                    
                    <!-- Visualization -->
                    <div class="card bg-white rounded-xl shadow-lg p-6">
                        <div class="text-green-500 text-3xl mb-4">
                            <i class="fas fa-project-diagram"></i>
                        </div>
                        <h3 class="text-xl font-bold mb-3">2. 业务逻辑的可视化表达</h3>
                        <p class="text-gray-700">状态机可以轻松地用图表表示，这使得开发团队和业务团队能够使用相同的语言进行沟通。</p>
                    </div>
                    
                    <!-- Stability -->
                    <div class="card bg-white rounded-xl shadow-lg p-6">
                        <div class="text-green-500 text-3xl mb-4">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                        <h3 class="text-xl font-bold mb-3">3. 状态隔离带来的稳定性</h3>
                        <p class="text-gray-700">每个状态只处理与自己相关的事件，这种隔离性使得修改某个状态的行为不会影响其他状态。</p>
                    </div>
                </div>
                
                <div class="mt-8 code-block">
                    <button class="copy-btn" onclick="copyCode(this)">
                        <i class="fas fa-copy"></i>
                    </button>
                    <pre><code class="language-typescript">// 清晰的状态机结构
interface OrderState {
  process(order: Order, event: OrderEvent): OrderState;
}

class NewOrderState implements OrderState {
  process(order: Order, event: OrderEvent): OrderState {
    switch (event.type) {
      case "PAYMENT_RECEIVED":
        order.updateStatus("PAID");
        sendConfirmationEmail(order);
        return new PaidOrderState();
      case "CANCEL":
        order.updateStatus("CANCELLED");
        refundPayment(order);
        return new CancelledOrderState();
      default:
        return this;
    }
  }
}</code></pre>
                </div>
            </section>

            <!-- Example Section -->
            <section id="example" class="mb-20">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-purple-500 pl-4">四、订单处理系统的重构</h2>
                
                <div class="grid md:grid-cols-2 gap-8">
                    <div>
                        <h3 class="text-2xl font-bold mb-4">1. 从混乱的if-else到优雅的状态机</h3>
                        <p class="text-gray-700 mb-6">让我们看看如何重构一个订单处理系统：</p>
                        
                        <div class="code-block mb-6">
                            <button class="copy-btn" onclick="copyCode(this)">
                                <i class="fas fa-copy"></i>
                            </button>
                            <pre><code class="language-python"># 重构前: if-else地狱
def process_order(order, event):
    if order.status == "new":
        if event == "payment_received":
            order.status = "paid"
            send_confirmation()
        elif event == "cancel":
            order.status = "cancelled"
    elif order.status == "paid":
        if event == "ship":
            if check_inventory():
                order.status = "shipped"
                update_inventory()
            else:
                order.status = "backorder"
                notify_customer()
        elif event == "refund_request":
            if within_refund_period():
                order.status = "refunding"
                process_refund()
            else:
                deny_refund()
    # 更多嵌套条件...</code></pre>
                        </div>
                    </div>
                    
                    <div>
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyCode(this)">
                                <i class="fas fa-copy"></i>
                            </button>
                            <pre><code class="language-python"># 重构后: 状态机模式
class OrderStateMachine:
    def __init__(self):
        self.states = {
            "new": NewOrderState(),
            "paid": PaidOrderState(),
            "shipped": ShippedOrderState(),
            "cancelled": CancelledOrderState(),
            # 其他状态...
        }
    
    def process(self, order, event):
        current_state = self.states[order.status]
        next_state_name = current_state.handle_event(order, event)
        if next_state_name != order.status:
            order.status = next_state_name

class NewOrderState:
    def handle_event(self, order, event):
        if event == "payment_received":
            send_confirmation()
            return "paid"
        elif event == "cancel":
            return "cancelled"
        return "new"  # 状态不变</code></pre>
                        </div>
                    </div>
                </div>
                
                <h3 class="text-2xl font-bold mt-12 mb-4">2. 状态定义与转换矩阵设计</h3>
                <p class="text-gray-700 mb-6">设计状态机时，首先要明确定义所有可能的状态和事件，然后创建转换矩阵，清晰地表示在每个状态下，每个事件会导致什么状态转换。</p>
                
                <div class="code-block mb-6">
                    <button class="copy-btn" onclick="copyCode(this)">
                        <i class="fas fa-copy"></i>
                    </button>
                    <pre><code class="language-javascript">// 转换矩阵示例
const transitionMatrix = {
  new: {
    payment_received: 'paid',
    cancel: 'cancelled'
  },
  paid: {
    ship: 'shipped',
    refund_request: 'refunding'
  },
  shipped: {
    deliver: 'delivered',
    return_request: 'returning'
  },
  // 更多状态转换...
};</code></pre>
                </div>
                
                <h3 class="text-2xl font-bold mt-12 mb-4">3. 处理边界情况的策略</h3>
                <p class="text-gray-700 mb-6">状态机设计中，处理非法状态转换和边界情况变得更加直观：</p>
                
                <div class="code-block">
                    <button class="copy-btn" onclick="copyCode(this)">
                        <i class="fas fa-copy"></i>
                    </button>
                    <pre><code class="language-java">public class OrderStateMachine {
    // ...
    
    public void process(Order order, Event event) {
        String currentState = order.getStatus();
        StateHandler handler = states.get(currentState);
        
        if (handler == null) {
            throw new IllegalStateException("Unknown order state: " + currentState);
        }
        
        try {
            String nextState = handler.handleEvent(order, event);
            if (!currentState.equals(nextState)) {
                // 记录状态转换
                logStateTransition(order, currentState, nextState, event);
                order.setStatus(nextState);
            }
        } catch (IllegalEventException e) {
            // 处理非法事件
            handleIllegalEvent(order, event, e);
        }
    }
}</code></pre>
                </div>
            </section>

            <!-- Implementation Section -->
            <section class="mb-20">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-yellow-500 pl-4">五、各种语言中实现状态机的方法</h2>
                
                <div class="grid md:grid-cols-3 gap-6">
                    <!-- JavaScript -->
                    <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="p-6">
                            <div class="flex items-center mb-4">
                                <div class="bg-yellow-100 text-yellow-800 p-2 rounded-lg mr-3">
                                    <i class="fab fa-js-square text-2xl"></i>
                                </div>
                                <h3 class="text-xl font-bold">JavaScript/TypeScript</h3>
                            </div>
                            
                            <div class="code-block">
                                <button class="copy-btn" onclick="copyCode(this)">
                                    <i class="fas fa-copy"></i>
                                </button>
                                <pre><code class="language-typescript">import { createMachine, interpret } from 'xstate';

const orderMachine = createMachine({
  id: 'order',
  initial: 'new',
  states: {
    new: {
      on: {
        PAYMENT_RECEIVED: 'paid',
        CANCEL: 'cancelled'
      }
    },
    paid: {
      on: {
        SHIP: 'shipped',
        REFUND_REQUEST: 'refunding'
      }
    },
    // 其他状态...
  }
});

const orderService = interpret(orderMachine)
  .onTransition(state => console.log(state.value))
  .start();

// 使用状态机
orderService.send('PAYMENT_RECEIVED'); // 状态变为 'paid'</code></pre>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Java -->
                    <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="p-6">
                            <div class="flex items-center mb-4">
                                <div class="bg-red-100 text-red-800 p-2 rounded-lg mr-3">
                                    <i class="fab fa-java text-2xl"></i>
                                </div>
                                <h3 class="text-xl font-bold">Java</h3>
                            </div>
                            
                            <div class="code-block">
                                <button class="copy-btn" onclick="copyCode(this)">
                                    <i class="fas fa-copy"></i>
                                </button>
                                <pre><code class="language-java">// 状态接口
interface OrderState {
    OrderState handlePaymentReceived(Order order);
    OrderState handleShipment(Order order);
    OrderState handleCancellation(Order order);
    // 其他事件处理方法...
}

// 具体状态实现
class NewOrderState implements OrderState {
    @Override
    public OrderState handlePaymentReceived(Order order) {
        order.sendConfirmationEmail();
        return new PaidOrderState();
    }
    
    @Override
    public OrderState handleShipment(Order order) {
        throw new IllegalStateException("Cannot ship an unpaid order");
    }
    
    @Override
    public OrderState handleCancellation(Order order) {
        order.cancelOrder();
        return new CancelledOrderState();
    }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Python -->
                    <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="p-6">
                            <div class="flex items-center mb-4">
                                <div class="bg-blue-100 text-blue-800 p-2 rounded-lg mr-3">
                                    <i class="fab fa-python text-2xl"></i>
                                </div>
                                <h3 class="text-xl font-bold">Python</h3>
                            </div>
                            
                            <div class="code-block">
                                <button class="copy-btn" onclick="copyCode(this)">
                                    <i class="fas fa-copy"></i>
                                </button>
                                <pre><code class="language-python">from transitions import Machine

class Order:
    states = ['new', 'paid', 'shipped', 'delivered', 'cancelled']
    
    def __init__(self):
        self.machine = Machine(
            model=self,
            states=self.states,
            initial='new'
        )
        
        # 定义转换
        self.machine.add_transition('pay', 'new', 'paid', before='process_payment')
        self.machine.add_transition('ship', 'paid', 'shipped', conditions=['check_inventory'])
        self.machine.add_transition('deliver', 'shipped', 'delivered')
        self.machine.add_transition('cancel', ['new', 'paid'], 'cancelled')
    
    def process_payment(self):
        print("Processing payment...")
    
    def check_inventory(self):
        print("Checking inventory...")
        return True  # 假设库存充足

# 使用
order = Order()
order.state  # 'new'
order.pay()
order.state  # 'paid'</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- Advanced Section -->
            <section class="mb-20">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-indigo-500 pl-4">六、状态机设计的进阶</h2>
                
                <div class="grid md:grid-cols-2 gap-8">
                    <div>
                        <h3 class="text-2xl font-bold mb-4">1. 分层状态机处理复杂业务</h3>
                        <p class="text-gray-700 mb-6">对于特别复杂的业务，可以使用分层状态机，让一个状态内部再包含一个完整的状态机：</p>
                        
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyCode(this)">
                                <i class="fas fa-copy"></i>
                            </button>
                            <pre><code class="language-javascript">const paymentProcessingMachine = {
  initial: 'validating',
  states: {
    validating: { on: { VALID: 'processing', INVALID: 'failed' } },
    processing: { on: { SUCCESS: 'completed', ERROR: 'failed' } },
    completed: { type: 'final' },
    failed: { type: 'final' }
  }
};

const orderMachine = {
  initial: 'new',
  states: {
    new: {
      on: { 
        START_PAYMENT: 'processingPayment' 
      }
    },
    processingPayment: {
      // 嵌套状态机
      machine: paymentProcessingMachine,
      on: {
        // 当内部状态机到达最终状态时的转换
        'completed': 'paid',
        'failed': 'paymentFailed'
      }
    },
    paid: { /* ... */ },
    paymentFailed: { /* ... */ }
  }
};</code></pre>
                        </div>
                    </div>
                    
                    <div>
                        <h3 class="text-2xl font-bold mb-4">2. 状态持久化与恢复策略</h3>
                        <p class="text-gray-700 mb-6">对于需要持久化的状态机，可以将当前状态和必要的上下文保存到数据库：</p>
                        
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyCode(this)">
                                <i class="fas fa-copy"></i>
                            </button>
                            <pre><code class="language-python">class PersistentStateMachine:
    def __init__(self, entity_id):
        self.entity_id = entity_id
        self.load_state()
        
    def load_state(self):
        # 从数据库加载状态
        state_data = db.query(f"SELECT state, context FROM state_machines WHERE id = {self.entity_id}")
        if state_data:
            self.current_state = state_data.state
            self.context = json.loads(state_data.context)
        else:
            self.current_state = 'initial'
            self.context = {}
    
    def transition(self, event):
        # 执行状态转换
        previous_state = self.current_state
        self.current_state = self.get_next_state(previous_state, event)
        
        # 持久化新状态
        db.execute(
            f"UPDATE state_machines SET state = '{self.current_state}', " +
            f"context = '{json.dumps(self.context)}' WHERE id = {self.entity_id}"
        )
        
        return self.current_state</code></pre>
                        </div>
                    </div>
                </div>
            </section>

            <!-- When to Use Section -->
            <section class="mb-12">
                <h2 class="text-3xl font-bold mb-8 border-l-4 border-gray-500 pl-4">七、何时该用状态机，何时不该用</h2>
                
                <div class="grid md:grid-cols-2 gap-8">
                    <div>
                        <h3 class="text-2xl font-bold mb-4">1. 适合状态机的场景分析</h3>
                        <p class="text-gray-700 mb-6">状态机特别适合以下场景：</p>
                        
                        <ul class="list-disc pl-6 text-gray-700 mb-6 space-y-2">
                            <li>工作流程管理（如订单处理、文档审批）</li>
                            <li>游戏角色AI</li>
                            <li>UI交互控制</li>
                            <li>协议实现（如TCP状态管理）</li>
                            <li>业务流程有明确的状态和转换规则</li>
                        </ul>
                        
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyCode(this)">
                                <i class="fas fa-copy"></i>
                            </button>
                            <pre><code class="language-python"># 游戏AI状态机示例
class EnemyAI:
    def __init__(self):
        self.state = 'patrol'
        
    def update(self, game_world):
        if self.state == 'patrol':
            self.patrol()
            if self.detect_player(game_world):
                self.state = 'chase'
        elif self.state == 'chase':
            self.chase_player(game_world)
            if self.in_attack_range(game_world):
                self.state = 'attack'
            elif not self.can_see_player(game_world):
                self.state = 'search'
        elif self.state == 'attack':
            self.attack_player()
            if not self.in_attack_range(game_world):
                self.state = 'chase'
        elif self.state == 'search':
            self.search_for_player()
            if self.detect_player(game_world):
                self.state = 'chase'
            elif self.search_timer > 10:
                self.state = 'patrol'</code></pre>
                        </div>
                    </div>
                    
                    <div>
                        <h3 class="text-2xl font-bold mb-4">2. 过度设计的警告信号</h3>
                        <p class="text-gray-700 mb-6">不是所有场景都适合使用状态机，以下情况可能是过度设计：</p>
                        
                        <ul class="list-disc pl-6 text-gray-700 mb-6 space-y-2">
                            <li>状态很少（少于3个）且转换简单</li>
                            <li>业务逻辑频繁变化，状态难以定义</li>
                            <li>系统行为不依赖于历史状态</li>
                        </ul>
                        
                        <h3 class="text-2xl font-bold mt-8 mb-4">3. 与其他设计模式的结合使用</h3>
                        <p class="text-gray-700 mb-6">状态机可以与其他设计模式结合使用，提供更强大的解决方案：</p>
                        
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyCode(this)">
                                <i class="fas fa-copy"></i>
                            </button>
                            <pre><code class="language-java">// 结合命令模式和状态模式
public class OrderProcessor {
    private OrderState currentState;
    private Queue&lt;Command&gt; commandQueue = new LinkedList&lt;&gt;();
    
    public void process() {
        while (!commandQueue.isEmpty()) {
            Command command = commandQueue.poll();
            try {
                OrderState newState = command.execute(currentState);
                if (newState != currentState) {
                    // 状态转换
                    currentState.onExit();
                    currentState = newState;
                    currentState.onEnter();
                }
            } catch (Exception e) {
                // 处理命令执行失败
                commandQueue.add(new ErrorRecoveryCommand(e));
            }
        }
    }
}</code></pre>
                        </div>
                    </div>
                </div>
                
                <div class="mt-12 bg-blue-50 rounded-xl p-8 border border-blue-200">
                    <p class="text-xl text-blue-800 font-medium">通过状态机设计，我们可以将复杂的业务逻辑转化为清晰可维护的代码结构。虽然学习曲线可能稍陡，但一旦掌握，它将成为你处理复杂状态转换的得力助手，让你的代码真正比if-else优雅100倍。</p>
                </div>
            </section>
        </div>
    </div>

    <script>
        // Initialize Mermaid
        mermaid.initialize({
            startOnLoad: true,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            }
        });
        
        // Copy code button functionality
        function copyCode(button) {
            const codeBlock = button.parentElement.querySelector('pre code');
            const range = document.createRange();
            range.selectNode(codeBlock);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand('copy');
            window.getSelection().removeAllRanges();
            
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check"></i>';
            setTimeout(() => {
                button.innerHTML = originalText;
            }, 2000);
        }
        
        // Smooth scrolling for anchor links
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });
    </script>
</body>
</html>
```